<?php
/*
 * Add a comment.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User is not authenticated.");
	echo json_encode($err);
	return;
}

if (!F3::exists('POST.recipe_id') || !F3::exists('POST.comment')):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Comment and recipe id are required.");
	echo json_encode($err);
	return;
endif;

// get user ID from session
$id = F3::get('SESSION.user_id');

// does recipe exist?
$rid = F3::get('POST.recipe_id');
$param = array('1'=>$rid);
$result = DB::sql("SELECT rid from recipes where rid = ?", $param);
if(count($result)==0):
	//the recipe doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe does not exist.");
	echo json_encode($err);
	return;
endif;

// does exact comment already exist?
$comment = F3::get('POST.comment');
$param = array('1'=>$comment);
$result = DB::sql("SELECT rid from comments where comment = ?", $param);
if(count($result)>0):
	//comment exists
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Comment already exists.");
	echo json_encode($err);
	return;
endif;

// add comment
$param = array('1'=>$id, '2'=>$rid, '3'=>$comment);
DB::sql("insert into comments(uid, rid, comment) values (?, ?, ?)",$param);

// success
header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "Comment added.";
echo json_encode($response);
return;
?>
